//
//  UITextView+Extension.swift
//  新浪微博
//
//  Created by 徐绩 on 16/5/1.
//  Copyright © 2016年 ayumi. All rights reserved.
//

import UIKit

extension UITextView {
    
    
    // 将表情图片转成表情字符串以发送到新浪微博
    var emoticonText: String? {
        var res = ""
        let attr = self.attributedText
        
        //遍历副文本中的内容
        attr.enumerateAttributesInRange(NSMakeRange(0, attr.length), options: []) { (dict, range, _) -> Void in
            
//            print(dict)
            if let atta = dict["NSAttachment"] as? XJTextAttachment{
            // 是表情，取到表情的描述字符串
                res += atta.emoticon?.chs ?? ""
            }else{
            // 不是表情，是文字 ，所以我们需要截取
                res += (attr.string as NSString).substringWithRange(range)
            }
        }
        return res
    }
    
    
    
    /**
     添加表情到当前textview
     */
    func insertEmoticon(emoticon: XJEmojiModel){
        
        //1.通过现有文字生成可变副文本
        let originalAttr = NSMutableAttributedString(attributedString: self.attributedText)
        
        //2.通过表情模型生成表情图片 --> 通过图片生成 NSTextAttachment --> 通过 attachment 生成一个 NSAttributedString
        let img = UIImage(named: "\(emoticon.fileName ?? "")/\(emoticon.png ?? "")", inBundle: XJEmojiKeyboardViewModel.sharedEmojiViewModel.emotionBundle, compatibleWithTraitCollection: nil)
        
        let attachment = XJTextAttachment()
        attachment.emoticon = emoticon
        attachment.image = img
        
        //设置图片大小
        let attachmentWH = self.font!.lineHeight
        attachment.bounds = CGRect(x: 0, y: -4, width: attachmentWH, height: attachmentWH)
        
        let attr = NSAttributedString(attachment: attachment)
        
        //3. 将第2部生成的 NSAttributedString 添加到第1步生成的 NSMutableAttributedString 里面
        //光标所在位置
        var selectedRange = self.selectedRange
        originalAttr.replaceCharactersInRange(selectedRange, withAttributedString: attr)
        
        //字体大小
        originalAttr.addAttribute(NSFontAttributeName, value: self.font!, range: NSMakeRange(0, originalAttr.length))
        self.attributedText = originalAttr
        
        //光标位置
        selectedRange.location += 1
        selectedRange.length = 0
        self.selectedRange = selectedRange
        
        //文字改变通知
    NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: self)
    delegate?.textViewDidChange?(self)
        
    }
}
